from utils import log_info, log_exception, log_error, log_debug
from typing import List, Optional
from .base_dao import BaseDAO
from models.favorite_question import FavoriteQuestion


class FavoriteQuestionDAO(BaseDAO[FavoriteQuestion]):
    """收藏题目表数据访问对象"""

    def __init__(self):
        """
        初始化FavoriteQuestionDAO
        """
        super().__init__(FavoriteQuestion)

    def _get_table_name(self) -> str:
        """获取表名"""
        return "favorite_questions"

    def _get_primary_key(self) -> str:
        """获取主键名"""
        return "id"

    def get_by_user_id(self, user_id: int) -> List[FavoriteQuestion]:
        """
        根据用户ID获取所有收藏题目
        :param user_id: 用户ID
        :return: 收藏题目实体列表
        """
        sql = "SELECT * FROM favorite_questions WHERE user_id = ?"
        results = self._execute_query(sql, (user_id,))
        log_debug(f"获取用户{user_id}的收藏题目成功，共{len(results)}条记录")
        return results

    def get_by_user_and_question(self, user_id: int, question_id: int) -> Optional[FavoriteQuestion]:
        """
        根据用户ID和题目ID获取收藏题目
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 收藏题目实体，如果不存在返回None
        """
        sql = "SELECT * FROM favorite_questions WHERE user_id = ? AND question_id = ?"
        result = self._execute_query(sql, (user_id, question_id), single_result=True)
        if not result:
            log_debug(f"未找到用户{user_id}的题目{question_id}的收藏记录")
        return result

    def get_by_user_and_category(self, user_id: int, category: str) -> List[FavoriteQuestion]:
        """
        根据用户ID和分类获取收藏题目
        :param user_id: 用户ID
        :param category: 题目分类
        :return: 收藏题目实体列表
        """
        sql = "SELECT * FROM favorite_questions WHERE user_id = ? AND category = ?"
        results = self._execute_query(sql, (user_id, category))
        log_debug(f"获取用户{user_id}分类{category}的收藏题目成功，共{len(results)}条记录")
        return results

    def delete_by_user_and_question(self, user_id: int, question_id: int) -> bool:
        """
        根据用户ID和题目ID删除收藏题目
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 删除成功返回True，否则返回False
        """
        try:
            conn = self._get_connection()
            if not conn:
                log_error("无法获取数据库连接")
                return False
            cursor = conn.cursor()
            cursor.execute(
                "DELETE FROM favorite_questions WHERE user_id = ? AND question_id = ?",
                (user_id, question_id)
            )
            conn.commit()
            if cursor.rowcount > 0:
                log_debug(f"删除用户{user_id}的题目{question_id}收藏成功")
                return True
            log_debug(f"未找到用户{user_id}的题目{question_id}的收藏记录，删除失败")
            return False
        except Exception as e:
            log_exception(f"删除收藏题目失败: {str(e)}")
            return False
        finally:
            if conn:
                self.db_pool.release_connection(conn)